/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mall.db.dao;

import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Iaroslav_Mazai
 */
public abstract class JpaDAO<T> implements CommonDAO<T> {

	private final String unitName = "MallPU";
	private EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName);
	private EntityManager em = emf.createEntityManager();

	@Override
	public T findById(Integer id) {
		return em.find(getEntityClass(), id);
	}

	protected EntityManager getEntityManager() {
		return em;
	}

	@Override
	public List<T> findAll() {
		CriteriaQuery query = em.getCriteriaBuilder().createQuery();
		query.select(query.from(getEntityClass()));
		return em.createQuery(query).getResultList();
	}

	@Override
	public void save(T entity) {
		em.getTransaction().begin();
		em.persist(entity);
		em.getTransaction().commit();
	}

	@Override
	public void update(T entity) {
		em.getTransaction().begin();
		em.merge(entity);
		em.getTransaction().commit();
	}

	@Override
	public void remove(T entity) {
		em.getTransaction().begin();
		em.remove(em.merge(entity));
		em.getTransaction().commit();
	}

	public abstract Class<T> getEntityClass();
}
